#include "sock_define.h"
ssize_t readn(int fd, void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nread;
	char *ptr;
	ptr =(char*) vptr;
	nleft = n;
	while(nleft>0)
	{
		if((nread = read(fd, vptr, nleft)) < 0 )
		{
			if(errno == EINTR)
				nread = 0;
			else
				return -1;			
		}
		else if(nread == 0)
			break;
		
		nleft = nleft - nread;
		ptr += nread;
	}
	return (n-nleft);
}
ssize_t writen(int fd, void *vptr, size_t n)
{
	size_t nleft;
	ssize_t nwrite;
	char *ptr;
	ptr = (char*) vptr;
	nleft = n;
	while(nwrite>0)
	{
		if((nwrite = write(fd, vptr, nleft)) <= 0 )
		{
			if(errno == EINTR)
				nwrite = 0;
			else
				return -1;			
		}
		else if(nwrite == 0)
			break;
		
		nleft = nleft - nwrite;
		ptr += nwrite;
	}
	return (n-nleft);
}

ssize_t readline(int fd, void *vptr, size_t maxlen)
{
	ssize_t n, rc;
	char c, *ptr;
	ptr = (char*)vptr;
	for(n = 1; n< maxlen ; n++)
	{
again:
		if((rc = read(fd, &c, 1) ) ==1 )
		{
			*ptr++ = c;
			if(c == '\n')
				break;/* a new line */
		}
		else if(rc == 0)
		{
			*ptr = 0;
			return (n-1);/* a EOF */
		}
		else
		{
			if(errno == EINTR)
				goto again;
			
			return -1;
		}									
	}
	*ptr = 0;/* last null*/
	return n;
}

void sig_chld(int signo)
{
	pid_t pid;
	int stat;
	while((pid = waitpid(-1, &stat, WNOHANG)) > 0)
	{
		printf("child %d terminated\n", pid);	
	}
	return ;
	
}
